const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa-cors')
const jwt = require('koa-jwt')

const _mongoConnect = require('./db/index')
const { secret } = require('./utils/config')
const { judge_token, judge_login } = require('./utils/judge_token')
const { nowDate } = require('./utils/index')

// 数据库连接
_mongoConnect()

const index = require('./routes/index')
const users = require('./routes/users')
const upload = require('./routes/upload')
const article = require('./routes/article')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({ enableTypes:['json', 'form', 'text'] }))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${nowDate(1)}操作----- ${ctx.method} ${ctx.url} - ${ms}ms`)
})



// 允许后端跨域
app.use(cors())

// 判断header authorization里面有没有token
app.use(judge_token)

// 配置白名单
app.use(jwt({ secret }).unless({
  path: ['/users/login', '/users/register']
}))

// 判断用户是否登录中间件
app.use(judge_login)


// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(upload.routes(), upload.allowedMethods())
app.use(article.routes(), article.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
